﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        SerialPort dataport = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One);
        public Form1()
        {
            InitializeComponent();
            dataport.DataReceived += new SerialDataReceivedEventHandler(dataport_DataReceived);

            updater = TextUpdate;
        }
        updateTextBox updater;
        Semaphore wait = new Semaphore(0, 1);
        private void button1_Click(object sender, EventArgs e)
        {
            readtoparse = false;  
            byte[] buffer = new byte[4];
            buffer[0] = 0x1B;
            buffer[1] = 0x1B;
            buffer[2] = 0x1B;
            buffer[3] = 0x1B;
            Buffer = "";


            if (!dataport.IsOpen)
            {
                textBox1.Text = "Port isn't Open";
                return;
                //dataport.DataReceived -= new SerialDataReceivedEventHandler(dataport_DataReceived);
                //dataport.Close();
            }

            
            
            dataport.Write(buffer,0,4);
            Thread.Sleep(1000);
            dataport.Write(buffer, 0, 1);
            Thread.Sleep(1000);
            dataport.Write(textBox2.Text + Environment.NewLine);

     

            Thread.Sleep(1000);
            dataport.Write(buffer, 0, 1);
            Thread.Sleep(100);
            dataport.Write(buffer, 0, 1);
            Thread.Sleep(100);
            dataport.Write(buffer, 0, 1);
            Thread.Sleep(100);
            dataport.Write(buffer, 0, 1);
            

            
            writeOutput = updateGetResponse;
            Thread getResposeThread = new Thread(new ThreadStart(getResponse));

            //getResposeThread.Start();
            
            
            //timer1.Interval = 1000;
            //timer1.Start();

        }
        updateTextBox writeOutput;
        void updateGetResponse()
        {
            textBox1.Text = Buffer2;
        }

        bool readtoparse;
        StringBuilder buffer2 = new StringBuilder();
        string Buffer2;
        void getResponse()
        {
            while (true)
            {
                //wait.
                if (readtoparse)
                {
                //    foreach (char item in Buffer)
                //    {
                //        if (item >= (char)32 && item <= (char)126)
                //        {
                //            buffer2.Append(item);
                //        }
                //    }

                    char[] items = Buffer.ToArray();
                    int first  =  Buffer.IndexOf(textBox2.Text);
                    int second =  Buffer.IndexOf(Environment.NewLine, first) + 2;
                    
                    int third  =  Buffer.IndexOf((char) 0x1B, second);
                    //int first = buffer2.ToString().IndexOf(textBox2.Text) + textBox2.Text.Length;
                    //int second = buffer2.ToString().IndexOf("[2J", first) - 2;

                    Buffer2 = Buffer.Substring(second, third - second);

                    this.Invoke(writeOutput);
                    readtoparse = false;
                }
            }
            
        }




        string Buffer;

        void dataport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort data = (SerialPort) sender;
            Buffer += data.ReadExisting();
            this.Invoke(updater);

            readtoparse = Regex.IsMatch(Buffer, "Exit HyperTerminal");



            if (readtoparse)
            {
                char[] items = Buffer.ToArray();
                int first = Buffer.IndexOf(textBox2.Text);
                int second = Buffer.IndexOf(Environment.NewLine, first) + 2;

                int third = Buffer.IndexOf((char)0x1B, second);
                //int first = buffer2.ToString().IndexOf(textBox2.Text) + textBox2.Text.Length;
                //int second = buffer2.ToString().IndexOf("[2J", first) - 2;

                Buffer2 = Buffer.Substring(second, third - second);

                this.Invoke(writeOutput);
                readtoparse = false;
            }
        
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            StringBuilder buffer2=new StringBuilder();
            foreach (char item in Buffer)
            {
                if (item >= (char)32 && item <= (char)126)
                {
                    buffer2.Append(item);
                }
            }
            
            
            textBox1.Text = buffer2.ToString();
        }

        private delegate void updateTextBox();

        private void TextUpdate()
        {
            StringBuilder buffer2 = new StringBuilder();
            foreach (char item in Buffer)
            {
                if (item >= (char)32 && item <= (char)126)
                {
                    buffer2.Append(item);
                }
            }
            textBox1.Text = buffer2.ToString();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                dataport.Open();
            }
            catch (Exception err)
            {

                textBox1.Text = err.Message;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                dataport.Close();
                //string pattern = @"\" + @textBox2.Text + @".*2J?";
                //string result = Regex.Match(textBox1.Text, pattern).Value;
                //int index1=Regex.Match(textBox1.Text.


                
                return;
            }
            catch (Exception err)
            {
                
                textBox1.Text = err.Message;
            }
        }
    }
}
